﻿//负责 MES 结果给 VisionMaster（TCP 客户端，发送数据到 9527 端口）。


using System;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ShangWeiDemo1
{
    /// <summary>
    /// 管理与 VisionMaster 的 TCP 客户端连接（用于发送 MES 结果）
    /// </summary>
    public class TcpClientManager
    {
        private TcpClient _tcpClient;
        private readonly Action<string> _logAction;
        private static readonly object _tcpLock = new object();

        // TCP Server 配置
        private const string TcpServerIp = "192.168.30.83";
        private const int TcpServerPort = 9527;

        public TcpClientManager(Action<string> logAction)
        {
            _logAction = logAction;
        }

        private void WriteToLogFile(string msg) => _logAction?.Invoke(msg);

        /// <summary>
        /// 确保 TCP 连接是打开的。如果未连接，则尝试连接。
        /// </summary>
        private bool EnsureTcpConnection()
        {
            lock (_tcpLock)
            {
                if (_tcpClient == null || !_tcpClient.Connected)
                {
                    // 先清理旧对象
                    if (_tcpClient != null)
                    {
                        _tcpClient.Close();
                        _tcpClient = null;
                    }

                    try
                    {
                        WriteToLogFile($"尝试连接 TCP 服务器：{TcpServerIp}:{TcpServerPort}");
                        _tcpClient = new TcpClient();

                        // 使用 BeginConnect/EndConnect 实现超时连接
                        IAsyncResult result = _tcpClient.BeginConnect(TcpServerIp, TcpServerPort, null, null);

                        // 等待连接完成，设置 5 秒超时
                        bool success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5));
                        if (success && _tcpClient.Client.Connected) // 检查 Connected 属性
                        {
                            _tcpClient.EndConnect(result);
                            WriteToLogFile("TCP 连接成功。");
                            return true;
                        }
                        else
                        {
                            if (success) _tcpClient.EndConnect(result); // 如果成功但未连接，调用 EndConnect
                            _tcpClient.Close();
                            _tcpClient = null;
                            WriteToLogFile("TCP 连接超时或失败。");
                            return false;
                        }
                    }
                    catch (Exception ex)
                    {
                        WriteToLogFile($"TCP 连接失败: {ex.Message}");
                        _tcpClient = null;
                        return false;
                    }
                }
                return true;
            }
        }

        /// <summary>
        /// 发送数据到 TCP Server
        /// </summary>
        /// <param name="data">要发送的字符串数据，例如："barcode,true"</param>
        public void SendDataToTcpServer(string data)
        {
            if (!EnsureTcpConnection())
            {
                WriteToLogFile("TCP 发送失败：无法建立连接。");
                return;
            }

            try
            {
                NetworkStream stream = _tcpClient.GetStream();
                // 假设您的 Server 期望 UTF8 编码的数据
                byte[] buffer = Encoding.UTF8.GetBytes(data + Environment.NewLine);
                // 写入数据
                stream.Write(buffer, 0, buffer.Length);

                // 关键：确保数据立即发送出去
                stream.Flush();

                WriteToLogFile($"TCP 发送成功：[{data}]");
            }
            catch (Exception ex)
            {
                WriteToLogFile($"TCP 发送过程中发生错误: {ex.Message}");

                // 发送失败后，断开连接，下次再尝试重连
                CloseConnection();
            }
        }

        /// <summary>
        /// 关闭 TCP 客户端连接
        /// </summary>
        public void CloseConnection()
        {
            lock (_tcpLock)
            {
                if (_tcpClient != null)
                {
                    try
                    {
                        _tcpClient.Close();
                    }
                    catch { }
                    _tcpClient = null;
                }
            }
        }
    }
}